package com.smbpics

import android.app.AlertDialog
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay
import kotlinx.coroutines.Job
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : AppCompatActivity() {
    private lateinit var smbClient: SmbClient
    private lateinit var fileAdapter: FileAdapter
    private lateinit var connectionSettings: ConnectionSettings
    private lateinit var imageLoader: ImageLoader

    private lateinit var imageViewLeft: ImageView
    private lateinit var imageViewRight: ImageView
    private lateinit var frameLeft: FrameLayout
    private lateinit var frameRight: FrameLayout
    private lateinit var tvLeftImageName: TextView
    private lateinit var tvLeftImageInfo: TextView
    private lateinit var tvRightImageName: TextView
    private lateinit var tvRightImageInfo: TextView
    private lateinit var tvPageInfo: TextView
    private lateinit var etSearch: EditText
    private lateinit var spinnerSort: Spinner
    private lateinit var layoutDualImage: LinearLayout
    private lateinit var layoutFileBrowser: LinearLayout
    private lateinit var recyclerViewFiles: RecyclerView

    private lateinit var btnConnect: Button
    private lateinit var btnPrevious: Button
    private lateinit var btnNext: Button
    private lateinit var btnAutoPlay: Button
    private lateinit var btnBrowse: Button
    private lateinit var btnBack: Button

    private var currentImages: List<SmbImageFile> = emptyList()
    private var currentIndex = 0
    private var currentDirectory = ""
    private var isConnected = false
    private var isBrowserMode = false
    private var isAutoPlayEnabled = false
    private var autoPlayJob: Job? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        smbClient = SmbClient()
        connectionSettings = ConnectionSettings(this)
        imageLoader = ImageLoader(this)
        initViews()
        setupSortSpinner()
        setupListeners()
        
        // Auto-connect to last saved connection
        autoConnectToLastServer()
    }

    private fun autoConnectToLastServer() {
        // Check if auto-connect is enabled and has saved connection
        if (!connectionSettings.isAutoConnectEnabled() || !connectionSettings.hasSavedConnection()) {
            return
        }
        
        val lastConnection = connectionSettings.getLastConnection()
        val stats = connectionSettings.getConnectionStats()
        
        // Show auto-connect indicator with connection history
        val connectMessage = if (stats.successCount > 0) {
            val dateFormat = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
            val lastTime = Date(stats.lastConnectionTime)
            "正在连接到上次的服务器 (上次: ${dateFormat.format(lastTime)})..."
        } else {
            "正在连接到上次的服务器..."
        }
        
        Toast.makeText(this, connectMessage, Toast.LENGTH_SHORT).show()
        
        lifecycleScope.launch {
            val connected = smbClient.connect(
                lastConnection.serverAddress,
                lastConnection.shareName,
                lastConnection.username,
                lastConnection.password
            )
            
            if (connected) {
                isConnected = true
                connectionSettings.recordConnectionSuccess()
                Toast.makeText(this@MainActivity, "自动连接成功", Toast.LENGTH_SHORT).show()
                updateButtonHighlight()
                loadImages()
            } else {
                isConnected = false
                Toast.makeText(this@MainActivity, "自动连接失败，请检查服务器或手动连接", Toast.LENGTH_SHORT).show()
                updateButtonHighlight()
            }
        }
    }

    private fun initViews() {
        imageViewLeft = findViewById(R.id.imageViewLeft)
        imageViewRight = findViewById(R.id.imageViewRight)
        frameLeft = findViewById(R.id.frameLeft)
        frameRight = findViewById(R.id.frameRight)
        tvLeftImageName = findViewById(R.id.tvLeftImageName)
        tvLeftImageInfo = findViewById(R.id.tvLeftImageInfo)
        tvRightImageName = findViewById(R.id.tvRightImageName)
        tvRightImageInfo = findViewById(R.id.tvRightImageInfo)
        tvPageInfo = findViewById(R.id.tvPageInfo)
        etSearch = findViewById(R.id.etSearch)
        spinnerSort = findViewById(R.id.spinnerSort)
        layoutDualImage = findViewById(R.id.layoutDualImage)
        layoutFileBrowser = findViewById(R.id.layoutFileBrowser)
        recyclerViewFiles = findViewById(R.id.recyclerViewFiles)

        // Initialize button references
        btnConnect = findViewById(R.id.btnConnect)
        btnPrevious = findViewById(R.id.btnPrevious)
        btnNext = findViewById(R.id.btnNext)
        btnAutoPlay = findViewById(R.id.btnAutoPlay)
        btnBrowse = findViewById(R.id.btnBrowse)
        btnBack = findViewById(R.id.btnBack)

        // Setup file browser
        fileAdapter = FileAdapter(smbClient) { file ->
            if (file.isDirectory) {
                currentDirectory = file.path
                loadImages()
            } else {
                // Switch to image view mode and show selected image
                isBrowserMode = false
                updateViewMode()
                val imageIndex = currentImages.indexOfFirst { it.path == file.path }
                if (imageIndex != -1) {
                    currentIndex = imageIndex
                    displayImages()
                }
            }
        }

        recyclerViewFiles.layoutManager = GridLayoutManager(this, 4)
        recyclerViewFiles.adapter = fileAdapter
    }

    private fun setupSortSpinner() {
        val sortOptions = arrayOf("名称升序", "名称降序", "大小升序", "大小降序", "日期升序", "日期降序", "类别升序", "类别降序")
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, sortOptions)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinnerSort.adapter = adapter
        spinnerSort.setSelection(5) // Default to "日期降序" for image mode

        spinnerSort.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                if (isConnected) {
                    loadImages()
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
    }

    private fun setupListeners() {
        btnConnect.setOnClickListener {
            if (isConnected) {
                // Disconnect from SMB server
                disconnectFromSmb()
            } else {
                // Show connection dialog
                showConnectionDialog()
            }
        }
        btnConnect.setOnFocusChangeListener { _, hasFocus ->
            updateButtonHighlight()
        }

        btnPrevious.setOnClickListener {
            if (currentIndex > 1) {
                currentIndex -= 2
                displayImages()
            }
        }
        btnPrevious.setOnFocusChangeListener { _, hasFocus ->
            updateButtonHighlight()
        }

        btnNext.setOnClickListener {
            if (currentIndex < currentImages.size - 2) {
                currentIndex += 2
                displayImages()
            }
        }
        btnNext.setOnFocusChangeListener { _, hasFocus ->
            updateButtonHighlight()
        }

        btnAutoPlay.setOnClickListener {
            toggleAutoPlay()
        }
        btnAutoPlay.setOnFocusChangeListener { _, hasFocus ->
            updateButtonHighlight()
        }

        btnBrowse.setOnClickListener {
            // Toggle mode when clicked
            isBrowserMode = !isBrowserMode
            updateViewMode()
        }
        btnBrowse.setOnFocusChangeListener { _, hasFocus ->
            updateButtonHighlight()
        }

        btnBack.setOnClickListener {
            navigateToParentDirectory()
        }
        btnBack.setOnFocusChangeListener { _, hasFocus ->
            updateButtonHighlight()
        }

        // Add focus listeners for image frames
        frameLeft.setOnFocusChangeListener { _, hasFocus ->
            frameLeft.isSelected = hasFocus
        }

        frameRight.setOnFocusChangeListener { _, hasFocus ->
            frameRight.isSelected = hasFocus
        }

        etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                if (isConnected) {
                    searchImages(s.toString())
                }
            }
        })
    }

    private fun toggleAutoPlay() {
        isAutoPlayEnabled = !isAutoPlayEnabled

        if (isAutoPlayEnabled) {
            startAutoPlay()
        } else {
            stopAutoPlay()
        }

        updateButtonHighlight()
    }

    private fun startAutoPlay() {
        stopAutoPlay() // Stop any existing auto-play

        if (!isConnected || isBrowserMode || currentImages.isEmpty()) {
            isAutoPlayEnabled = false
            updateButtonHighlight()
            return
        }

        autoPlayJob = lifecycleScope.launch {
            while (isAutoPlayEnabled) {
                delay(2000) // Wait 2 seconds

                if (isAutoPlayEnabled && !isBrowserMode && currentImages.isNotEmpty()) {
                    // Go to next page if available
                    if (currentIndex < currentImages.size - 2) {
                        currentIndex += 2
                        displayImages()
                    } else {
                        // Loop back to beginning
                        currentIndex = 0
                        displayImages()
                    }
                }
            }
        }
    }

    private fun stopAutoPlay() {
        autoPlayJob?.cancel()
        autoPlayJob = null
    }

    private fun updateButtonHighlight() {
        // Update connection button based on connection status
        btnConnect.isSelected = isConnected
        btnConnect.text = if (isConnected) "断开连接" else "连接"

        // Add focus highlight for TV navigation
        btnConnect.isFocusable = true

        // Always enable connect button for both connect and disconnect
        btnConnect.isEnabled = true

        // Update auto-play button based on state
        btnAutoPlay.isSelected = isAutoPlayEnabled
        btnAutoPlay.text = if (isAutoPlayEnabled) "停止播放" else "自动播放"
        btnAutoPlay.isFocusable = true
        btnAutoPlay.isEnabled = isConnected && !isBrowserMode

        // Update browse button - always enabled and selectable
        btnBrowse.isSelected = isBrowserMode
        btnBrowse.text = if (isBrowserMode) "图片模式" else "浏览模式"
        btnBrowse.isFocusable = true
        btnBrowse.isEnabled = true  // Always enabled in both modes

        // Update back button - always enabled and selectable when connected
        // Only disabled when not connected or at root directory
        val canGoBack = isConnected && currentDirectory.isNotEmpty()
        btnBack.isEnabled = isConnected  // Always enabled when connected, regardless of mode
        btnBack.isFocusable = isConnected
        btnBack.alpha = if (canGoBack) 1.0f else (if (isConnected) 0.7f else 0.5f)

        // Update navigation buttons based on availability and current state
        val canGoPrevious = currentIndex > 1
        val canGoNext = currentIndex < currentImages.size - 2

        btnPrevious.isEnabled = canGoPrevious
        btnNext.isEnabled = canGoNext
        btnPrevious.isFocusable = canGoPrevious
        btnNext.isFocusable = canGoNext

        // Visual feedback for enabled/disabled state
        btnPrevious.alpha = if (canGoPrevious) 1.0f else 0.5f
        btnNext.alpha = if (canGoNext) 1.0f else 0.5f
        
        // Only set focus on connect button when not connected
        // Let user manually choose focus in other cases to avoid automatic mode switching
        if (!isConnected) {
            btnConnect.requestFocus()
        }
        // Remove automatic focus switching to prevent unwanted mode changes
    }

    private fun showConnectionDialog() {
        val dialogView = layoutInflater.inflate(R.layout.connection_dialog, null)
        val dialog = AlertDialog.Builder(this)
            .setView(dialogView)
            .create()

        // Load saved connection settings
        val lastConnection = connectionSettings.getLastConnection()
        val serverInput = dialogView.findViewById<EditText>(R.id.etServerAddress)
        val shareInput = dialogView.findViewById<EditText>(R.id.etShareName)
        val usernameInput = dialogView.findViewById<EditText>(R.id.etUsername)
        val passwordInput = dialogView.findViewById<EditText>(R.id.etPassword)
        val autoConnectSwitch = dialogView.findViewById<Switch>(R.id.switchAutoConnect)
        
        // Set connection history
        serverInput.setText(lastConnection.serverAddress)
        shareInput.setText(lastConnection.shareName)
        usernameInput.setText(lastConnection.username)
        passwordInput.setText(lastConnection.password)
        autoConnectSwitch.isChecked = connectionSettings.isAutoConnectEnabled()
        
        // Add focus change listeners for TV navigation
        serverInput.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                serverInput.setBackgroundResource(R.drawable.search_background_focused)
            } else {
                serverInput.setBackgroundResource(R.drawable.search_background)
            }
        }
        
        shareInput.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                shareInput.setBackgroundResource(R.drawable.search_background_focused)
            } else {
                shareInput.setBackgroundResource(R.drawable.search_background)
            }
        }

        val clearButton = dialogView.findViewById<Button>(R.id.btnClear)
        clearButton.setOnClickListener {
            connectionSettings.clearConnection()
            serverInput.setText("")
            shareInput.setText("")
            usernameInput.setText("")
            passwordInput.setText("")
            autoConnectSwitch.isChecked = false
            Toast.makeText(this, "连接设置已清除", Toast.LENGTH_SHORT).show()
        }

        dialogView.findViewById<Button>(R.id.btnCancel).setOnClickListener {
            dialog.dismiss()
        }

        val connectButton = dialogView.findViewById<Button>(R.id.btnConnect)
        connectButton.setOnClickListener {
            val serverAddress = serverInput.text.toString().trim()
            val shareName = shareInput.text.toString().trim()
            val username = usernameInput.text.toString().trim()
            val password = passwordInput.text.toString().trim()

            if (serverAddress.isNotEmpty() && shareName.isNotEmpty()) {
                // Save connection settings with auto-connect preference
                val config = SmbConnectionConfig(serverAddress, shareName, username, password)
                connectionSettings.saveConnection(config)
                connectionSettings.setAutoConnect(autoConnectSwitch.isChecked)
                
                val stats = connectionSettings.getConnectionStats()
                val saveMessage = if (stats.successCount > 0) {
                    "连接设置已保存 (历史成功: ${stats.successCount}次)"
                } else {
                    "连接设置已保存"
                }
                Toast.makeText(this, saveMessage, Toast.LENGTH_SHORT).show()
                
                connectToSmb(serverAddress, shareName, username, password)
                dialog.dismiss()
            } else {
                Toast.makeText(this, "请填写服务器地址和共享名称", Toast.LENGTH_SHORT).show()
                serverInput.requestFocus()
            }
        }

        dialog.setOnShowListener {
            // Set proper focus for TV navigation
            if (serverInput.text.isEmpty()) {
                serverInput.requestFocus()
            } else {
                connectButton.requestFocus()
            }
        }

        dialog.show()
    }

    private fun connectToSmb(serverAddress: String, shareName: String, username: String, password: String) {
        lifecycleScope.launch {
            val connected = smbClient.connect(serverAddress, shareName, username, password)
            if (connected) {
                isConnected = true
                connectionSettings.recordConnectionSuccess()

                val stats = connectionSettings.getConnectionStats()
                val successMessage = "连接成功 (成功次数: ${stats.successCount})"
                Toast.makeText(this@MainActivity, successMessage, Toast.LENGTH_SHORT).show()

                updateButtonHighlight()
                loadImages()
            } else {
                isConnected = false
                Toast.makeText(this@MainActivity, "连接失败，请检查服务器设置", Toast.LENGTH_SHORT).show()
                updateButtonHighlight()
            }
        }
    }

    private fun disconnectFromSmb() {
        lifecycleScope.launch {
            smbClient.disconnect()
            isConnected = false
            currentImages = emptyList()
            currentIndex = 0
            currentDirectory = ""

            // Clear image views
            clearImageView(imageViewLeft, tvLeftImageName, tvLeftImageInfo)
            clearImageView(imageViewRight, tvRightImageName, tvRightImageInfo)
            tvPageInfo.text = "0 / 0"

            // Clear file browser
            fileAdapter.submitList(emptyList())

            Toast.makeText(this@MainActivity, "已断开连接", Toast.LENGTH_SHORT).show()
            updateButtonHighlight()
        }
    }

    private fun loadImages() {
        if (!isConnected) return

        lifecycleScope.launch {
            val sortType = when (spinnerSort.selectedItemPosition) {
                0 -> SortType.NAME_ASC
                1 -> SortType.NAME_DESC
                2 -> SortType.SIZE_ASC
                3 -> SortType.SIZE_DESC
                4 -> SortType.DATE_ASC
                5 -> SortType.DATE_DESC
                6 -> SortType.CATEGORY_ASC
                7 -> SortType.CATEGORY_DESC
                else -> SortType.CATEGORY_DESC
            }

            currentImages = smbClient.listImages(currentDirectory, sortType)
            currentIndex = 0

            if (isBrowserMode) {
                fileAdapter.submitList(currentImages)
            } else {
                displayImages()
            }
            updateButtonHighlight()
        }
    }

    private fun searchImages(query: String) {
        if (!isConnected || query.isEmpty()) {
            loadImages()
            return
        }

        lifecycleScope.launch {
            val sortType = when (spinnerSort.selectedItemPosition) {
                0 -> SortType.NAME_ASC
                1 -> SortType.NAME_DESC
                2 -> SortType.SIZE_ASC
                3 -> SortType.SIZE_DESC
                4 -> SortType.DATE_ASC
                5 -> SortType.DATE_DESC
                6 -> SortType.CATEGORY_ASC
                7 -> SortType.CATEGORY_DESC
                else -> SortType.CATEGORY_DESC
            }

            currentImages = smbClient.searchImages(query, currentDirectory, sortType)
            currentIndex = 0

            if (isBrowserMode) {
                fileAdapter.submitList(currentImages)
            } else {
                displayImages()
            }
            updateButtonHighlight()
        }
    }

    private fun updateViewMode() {
        if (isBrowserMode) {
            // In browse mode: completely hide image frames, maximize file browser
            layoutDualImage.visibility = View.GONE
            layoutFileBrowser.visibility = View.VISIBLE
            btnBrowse.text = "图片模式"

            // Stop auto-play when switching to browse mode
            if (isAutoPlayEnabled) {
                isAutoPlayEnabled = false
                stopAutoPlay()
            }

            // Set default sort for browse mode: Category Ascending
            spinnerSort.setSelection(6) // "类别升序"

            // Maximize browse display area by adjusting layout weights
            maximizeBrowseDisplay()

            // Set browse mode background color - dark gray
            layoutFileBrowser.setBackgroundColor(0xFF2A2A2A.toInt())

            // Ensure RecyclerView is visible and has proper background
            recyclerViewFiles.setBackgroundColor(0xFF2A2A2A.toInt())
            recyclerViewFiles.visibility = View.VISIBLE

            // Always refresh content in browse mode
            refreshBrowseContent()
        } else {
            // In image mode: hide file browser, maximize image frames
            layoutDualImage.visibility = View.VISIBLE
            layoutFileBrowser.visibility = View.GONE
            btnBrowse.text = "浏览模式"

            // Set default sort for image mode: Date Descending
            spinnerSort.setSelection(5) // "日期降序"

            // Maximize image display area by adjusting layout weights
            maximizeImageDisplay()

            // Set image mode background color - black
            layoutDualImage.setBackgroundColor(0xFF000000.toInt())

            // Always refresh content in image mode
            refreshImageContent()
        }
        updateButtonHighlight()
    }

    private fun refreshBrowseContent() {
        if (!isConnected) return

        // Ensure RecyclerView is properly configured for browse mode
        recyclerViewFiles.adapter = fileAdapter
        recyclerViewFiles.visibility = View.VISIBLE

        // Always use loadImages to ensure proper data flow
        // but also immediately update the UI with any existing data
        if (currentImages.isNotEmpty()) {
            // Immediately update the file adapter with existing data
            fileAdapter.submitList(currentImages.toList())
            fileAdapter.notifyDataSetChanged()
        }

        // Always load fresh data to ensure everything is up to date
        loadImages()
    }

    private fun refreshImageContent() {
        if (!isConnected) return

        // Always use loadImages to ensure proper data flow
        // but also immediately update the UI with any existing data
        if (currentImages.isNotEmpty()) {
            // Immediately display existing images
            displayImages()
        }

        // Always load fresh data to ensure everything is up to date
        loadImages()
    }

    private fun maximizeBrowseDisplay() {
        // In browse mode, give maximum space to file browser
        val fileBrowserParams = layoutFileBrowser.layoutParams as LinearLayout.LayoutParams
        fileBrowserParams.weight = 1.0f
        fileBrowserParams.height = 0
        layoutFileBrowser.layoutParams = fileBrowserParams

        // Ensure image display has no weight and no space when hidden
        val imageLayoutParams = layoutDualImage.layoutParams as LinearLayout.LayoutParams
        imageLayoutParams.weight = 0.0f
        imageLayoutParams.height = 0  // Completely collapse height
        layoutDualImage.layoutParams = imageLayoutParams

        // Request layout update to ensure changes take effect
        layoutFileBrowser.requestLayout()
        layoutDualImage.requestLayout()
    }

    private fun maximizeImageDisplay() {
        // In image mode, give maximum space to image display
        val imageLayoutParams = layoutDualImage.layoutParams as LinearLayout.LayoutParams
        imageLayoutParams.weight = 1.0f
        imageLayoutParams.height = 0  // Use weight instead of fixed height
        layoutDualImage.layoutParams = imageLayoutParams

        // Ensure file browser has no weight and no space when hidden
        val fileBrowserParams = layoutFileBrowser.layoutParams as LinearLayout.LayoutParams
        fileBrowserParams.weight = 0.0f
        fileBrowserParams.height = 0  // Completely collapse height
        layoutFileBrowser.layoutParams = fileBrowserParams

        // Request layout update to ensure changes take effect
        layoutDualImage.requestLayout()
        layoutFileBrowser.requestLayout()
    }

    private fun displayImages() {
        if (currentImages.isEmpty()) return

        val leftIndex = currentIndex
        val rightIndex = currentIndex + 1

        // Update page info
        val totalPages = (currentImages.size + 1) / 2
        val currentPage = (currentIndex / 2) + 1
        tvPageInfo.text = "$currentPage / $totalPages"

        // Display left image
        if (leftIndex < currentImages.size) {
            val leftImage = currentImages[leftIndex]
            displaySingleImage(leftImage, imageViewLeft, tvLeftImageName, tvLeftImageInfo, true)
        } else {
            clearImageView(imageViewLeft, tvLeftImageName, tvLeftImageInfo)
        }

        // Display right image
        if (rightIndex < currentImages.size) {
            val rightImage = currentImages[rightIndex]
            displaySingleImage(rightImage, imageViewRight, tvRightImageName, tvRightImageInfo, false)
        } else {
            clearImageView(imageViewRight, tvRightImageName, tvRightImageInfo)
        }

        updateButtonHighlight()
    }

    private fun displaySingleImage(
        imageFile: SmbImageFile,
        imageView: ImageView,
        nameView: TextView,
        infoView: TextView,
        isLeft: Boolean
    ) {
        nameView.text = imageFile.name
        infoView.text = formatFileInfo(imageFile)

        lifecycleScope.launch {
            val imageData = smbClient.downloadImage(imageFile.path)
            imageData?.let { data ->
                imageLoader.loadImage(data, imageView, imageFile.name)
            }
        }
    }

    private fun clearImageView(imageView: ImageView, nameView: TextView, infoView: TextView) {
        imageView.setImageDrawable(null)
        nameView.text = ""
        infoView.text = ""
    }

    private fun formatFileInfo(file: SmbImageFile): String {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
        val date = Date(file.lastModified)
        val size = formatFileSize(file.size)
        return "$size | ${dateFormat.format(date)}"
    }

    private fun formatFileSize(bytes: Long): String {
        return when {
            bytes < 1024 -> "$bytes B"
            bytes < 1024 * 1024 -> "${bytes / 1024} KB"
            bytes < 1024 * 1024 * 1024 -> "${bytes / (1024 * 1024)} MB"
            else -> "${bytes / (1024 * 1024 * 1024)} GB"
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stopAutoPlay()
        smbClient.disconnect()
    }

    private fun navigateToParentDirectory() {
        if (!isConnected) {
            Toast.makeText(this, "请先连接到服务器", Toast.LENGTH_SHORT).show()
            return
        }

        // Navigate to parent directory
        if (currentDirectory.isNotEmpty()) {
            val parentPath = getParentDirectory(currentDirectory)
            currentDirectory = parentPath
            loadImages()
            updateButtonHighlight()

            val message = if (parentPath.isEmpty()) {
                "已返回到根目录"
            } else {
                "已返回到上级目录"
            }
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
        } else {
            // Already at root directory
            Toast.makeText(this, "已在根目录", Toast.LENGTH_SHORT).show()
        }
    }

    private fun getParentDirectory(path: String): String {
        if (path.isEmpty() || path == "/") {
            return ""
        }

        val normalizedPath = path.trimEnd('/')
        val lastSlashIndex = normalizedPath.lastIndexOf('/')

        return if (lastSlashIndex <= 0) {
            ""
        } else {
            normalizedPath.substring(0, lastSlashIndex)
        }
    }
}